package com.hnust.root.service.impl.forward.wx;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hnust.root.common.util.ComUtil;
import com.hnust.root.dao.entity.domain.forward.Banner;
import com.hnust.root.dao.entity.domain.forward.Topic;
import com.hnust.root.dao.entity.domain.forward.WxUserInfo;
import com.hnust.root.dao.mapper.wx.BannerMapper;
import com.hnust.root.dao.mapper.wx.TopicMapper;
import com.hnust.root.dao.mapper.wx.WxUserInfoMapper;
import com.hnust.root.service.forword.wx.*;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
public class TopicServiceImp extends ServiceImpl<TopicMapper, Topic> implements TopicService {

    @Autowired
    private TopicMapper topicMapper;

    @Autowired
    private WxUserInfoMapper userInfoMapper;

    @Autowired
    private UserLikeService userLikeService;

    @Autowired
    private WxUserInfoService userInfoService;

    @Autowired
    private BannerMapper bannerMapper;

    @Autowired
    private CommentService commentService;

    @Autowired
    private ReplyService replyService;

    @Autowired
    private MessageService messageService;

    //发布话题
    @Override
    public Topic addTopic(Topic topic) {
        Date date = new Date();
        topic.setCreateTime(date);
        topic.setUpdatedAt(date);
        boolean res =  save(topic);
        return res ? topic : null;
    }

    @Override
    public IPage<Topic> getTopTopicList(IPage<Topic> page, String university) {
        page = topicMapper.selectPage(page, new QueryWrapper<Topic>()
                .eq("university", university)
                .eq("status", 0)
                .orderByDesc("update_time"));
        page.getRecords().forEach(topic -> {
            topic.setUserInfo(userInfoMapper.selectOne(new QueryWrapper<WxUserInfo>().eq("open_id", topic.getOpenId())));
            topic.setHasLiked(userLikeService.userHasLiked(topic.getOpenId(), topic.getId()));
        });
        return page;
    }

    @Override
    public boolean updateTopicById(Topic topic) {
        return ComUtil.DBisSuccess(topicMapper.updateById(topic));
    }

    @Override
    public Topic getTopicById(int id) {

        Topic topic = topicMapper.selectById(id);
        if (topic != null) {
            topic.setUserInfo(userInfoService.getUserInfoByOpenId(topic.getOpenId()));
        }
        return topic;
    }

    //通过openId获取用户的话题列表
    @Override
    public List<Topic> getTopicListByUserId(String openId) {
        List<Topic> list =  topicMapper.selectList(new QueryWrapper<Topic>()
                .eq("open_id", openId)
                .notIn("status", 1)
                .orderByDesc("create_time"));
        WxUserInfo userInfo = userInfoMapper.selectOne(new QueryWrapper<WxUserInfo>().eq("open_id", openId));
        list.forEach(topic -> {
            topic.setUserInfo(userInfo);
            topic.setHasLiked(userLikeService.userHasLiked(topic.getOpenId(), topic.getId()));
        });
        return list;
    }

    @Override
    public List<Banner> getBanner(String openId) {
        WxUserInfo userInfo = userInfoService.getUserInfoByOpenId(openId);
        if (userInfo != null) {
            return getBannerByUniversity(userInfo.getUniversity());
        }
        return new ArrayList<>();
    }

    @Cacheable(cacheNames = "mydemo:banner",key = "#university")
    //通过大学名称获取banner，包括所有人可见的banner
    @Override
    public List<Banner> getBannerByUniversity(String university) {
        return bannerMapper.selectList(new QueryWrapper<Banner>()
                .eq("university", university)
                .or()
                .eq("type", 0)
        .orderByAsc("position"));
    }

    //根据话题ID删除话题，同时删除对应的数据
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean deleteTopicById(int topicId) {
        Topic topic = getTopicById(topicId);
        //设置为已删除状态
        topic.setStatus(1);
        boolean res = updateTopicById(topic);
        //删除用户点赞记录
        userLikeService.deleteUserLikeByTopicId(topicId);
        //删除用户评论记录
        commentService.deleteComentByTopicId(topicId);
        //删除用户回复记录
        replyService.deleteReplyByTopicId(topicId);
        //删除用户消息
        messageService.deleteMsgByTopicId(topicId);
        return res;
    }

    //定时删除被删除的话题
    @Scheduled(fixedRate = 3600)
    private void deleteTopic() {
        topicMapper.scheduledDeleteTopic();
    }
}
